package artid.com.arttogoa.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

public class AppParser extends BasicParser {

	private final Class<? extends AppItem> cls;

	private List<AppItem> list = new ArrayList<AppItem>();
	private AppItem data;
	private String totalAmount;
	private int count;
	private String jsonData;

	public AppParser(Class<? extends AppItem> cls) {
		this.cls = cls;
	}

	@Override
	public void parse(String json) {
		jsonData = json;
		super.parse(json);

		if (getCode() == Success) {
			Object obj = getObject(getObj());
			if (obj == null) {
				return;
			}

			if (obj instanceof JSONObject) {
				parseData((JSONObject) obj);
			}
			if (obj instanceof JSONArray) {
				parseList((JSONArray) obj);
			}
		}
	}

	private Object getObject(JSONObject obj) {
		Object dest = null;
		if (cls == AppItem.class) {// 基础参数
			return obj;
		}
		return dest;
	}

	private void parseList(JSONArray array) {
		if (cls == AppItem.class) {
			return;
		}
		if (null == array || array.length() == 0) {
			return;
		}
		int len = array.length();
		for (int i = 0; i < len; i++) {
			JSONObject obj = array.optJSONObject(i);
			try {
				AppItem item = (AppItem) cls.newInstance();
				item.parse(obj);
				// System.out.println(obj.toString());
				list.add(item);
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	private void parseData(JSONObject obj) {
		if (cls == AppItem.class) {
			return;
		}
		if (obj == null) {
			return;
		}
		try {
			data = (AppItem) cls.newInstance();
			data.parse(obj);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	public List<? extends AppItem> getList() {
		return list;
	}

	public AppItem getData() {
		return data;
	}

	public Class<? extends AppItem> getCls() {
		return cls;
	}

	public int getMessageCount() {
		return count;
	}

	public String getTotalCount() {
		return totalAmount;
	}

	public String getJsonData() {
		return jsonData;
	}
	// private MessageItem mMessageItem;
	//
	// public void setMessageItem(MessageItem item) {
	// mMessageItem = item;
	// }
	//
	// public MessageItem getMessageItem() {
	// return mMessageItem;
	// }

}
